const xml2js = require('xml2js')
const xmlParser = new xml2js.Parser()
module.exports = parseMsg = (xmlmsg) => {
    return new Promise((reslove, reject) => {
        try {
            xmlParser.parseString(xmlmsg, (err, res) => {
                // console.log(res)
                if (res.xml.MsgType == 'event') {
                    const callbackData = {
                        ToUserName: res.xml.ToUserName,
                        FromUserName: res.xml.FromUserName,
                        MsgType: res.xml.MsgType,
                        CreateTime: res.xml.CreateTime,
                        Event: res.xml.Event,
                        EventKey: res.xml.EventKey
                    }
                    reslove(callbackData)
                } else if (res.xml.MsgType == 'text') {
                    const callbackData = {
                        ToUserName: res.xml.ToUserName,
                        FromUserName: res.xml.FromUserName,
                        MsgType: res.xml.MsgType,
                        CreateTime: res.xml.CreateTime,
                        Content: res.xml.Content,
                        MsgId: res.xml.MsgId
                    }
                    reslove(callbackData)
                } else if (res.xml.MsgType == 'image') {
                    const callbackData = {
                        ToUserName: res.xml.ToUserName,
                        FromUserName: res.xml.FromUserName,
                        MsgType: res.xml.MsgType,
                        CreateTime: res.xml.CreateTime,
                        PicUrl: res.xml.PicUrl,
                        MsgId: res.xml.MsgId,
                        MediaId: res.xml.MediaId
                    }
                    reslove(callbackData)
                }
            })

        } catch (error) {
            const callbackData = {
                ToUserName: null,
                FromUserName: null,
                MsgType: null,
                CreateTime: null,
                Content: null,
                MsgId: null
            }
            reslove(callbackData)
        }

    })
}